const User = require('../models/user')
const jwt = require('jsonwebtoken')
const { privateKey } = require('../configs/auth')

exports.register = async (req, res) => {
	const { email, password } = req.body

	// 插入文档
	const user = await User.create({
		email,
		password
	})

	// 返回注册的用户
	res.json({
		code: 200,
		data: {
			userinfo: user
		},
		msg: '注册成功'
	})
}

/**
* @api {post} account/login 登录
* @apiVersion 1.0.0
* @apiName login
* @apiGroup account模块
* @apiParam {String} email 邮箱号
* @apiParam {String} password  密码
* @apiSuccess {Number} code 结果标识
* @apiSuccess {String} msg 结果说明
* @apiSuccess {Object} data 用户信息
* @apiSuccess {String} token 用户信息
* @apiSuccessExample Success-Response:
* 
*  {
		code: 200,
		msg: "登录成功",
		data: { },
		token:"凭证"
}
*/
exports.login = async (req, res) => {
	const { email, password } = req.body

	// 查找用户
	const user = await User.findOne({
		email: email,
	})
	console.log(user);
	// 找不到用户
	if (!user) {
		return res.status(422).send({
			message: '用户名不存在'
		})
	}
	// 密码不正确
	if (!require('bcrypt').compareSync(
		password,
		user.password
	)) {
		return res.status(422).send({
			message: '密码无效'
		})
	}
	// 生成jwt
	const token = jwt.sign({
		id: String(user._id),
	}, privateKey)
	// 返回用户和jwt
	res.json({
		code: 200,
		msg: "登录成功",
		userinfo: user,
		token
	})
}